<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/2/20
 * 描述:
 */

namespace app\result\chat;

use app\model\chat\ChatConversations;
use app\model\chat\ChatConversationsSummary;
use app\model\chat\ChatMessages;
use app\result\BaseResult;
use GatewayClient\Gateway;
use think\Exception;
use think\facade\Db;

class WorkerResult extends BaseResult
{
    /**
     * 获取摘要信息
     * @param mixed $toUserId
     * @param mixed $conversation_id
     * @param mixed $messageId
     * @param ChatConversationsSummary $modelConversationsSummary
     * @param bool $is_online
     * @return void
     * @throws Exception
     */
    private function _getSummaryInfo(mixed $toUserId, mixed $conversation_id, mixed $messageId, ChatConversationsSummary $modelConversationsSummary, bool $is_online = false): void
    {
        $toSummaryData = [
            'user_id' => $toUserId,
            'conversation_id' => $conversation_id,
            'latest_message_id' => $messageId,
            'latest_message_time' => date('Y-m-d H:i:s'),
            'is_deleted' => 0,
            'read_time' => $is_online ? time() : 0,
        ];
        $hasToSummaryId = $modelConversationsSummary->where([
            'user_id' => $toUserId,
            'conversation_id' => $conversation_id,
        ])->value('id');
        if ($hasToSummaryId) {
            $modelConversationsSummary->data_update(['id' => $hasToSummaryId], $toSummaryData);
        } else {
            $hasToSummaryId = $modelConversationsSummary->data_add($toSummaryData);
            if (!$hasToSummaryId) {
                throw new Exception('会话摘要保存失败');
            }
        }
        //未读数加1
        if (!$is_online) {
            (new ChatConversationsSummary())->where(['id' => $hasToSummaryId])->inc('unread_count', 1)->save();
        }
    }

    /**
     * 保存消息
     * @param $messageData array 消息数据 [
     *  'user_id' => '发送者id',
     *    'to_user_id' => '接收者id',
     *    'type' => '消息类型',
     *    'content' => '消息内容',
     *
     * ]
     * @return array
     */
    public function add_message(array $messageData)
    {
        $modelConversations = new ChatConversations();
        $modelMessage = new ChatMessages();
        $modelConversationsSummary = new ChatConversationsSummary();
        $formUserId = $messageData['user_id'] ?? '0';//发送者id
        $toUserId = $messageData['to_id'] ?? '0';//接收者id，0=平台
        $user_ids = [$formUserId, $toUserId];
        //user_ids按从小到大
        sort($user_ids);
        $user_ids = join(',', $user_ids);//组装user_ids
        Db::startTrans();
        try {
            $conversation_id = $modelConversations->where('user_ids', $user_ids)->value('conversation_id');
            $conversationData = [
                'latest_message_time' => date('Y-m-d H:i:s'),
            ];
            if (!$conversation_id) {
                $conversationData['user_ids'] = $user_ids;
                $conversation_id = $modelConversations->data_add($conversationData);
                if (!$conversation_id) {
                    throw new Exception('会话保存失败');
                }
            } else {
                $modelConversations->data_update(['conversation_id' => $conversation_id], $conversationData);
            }
            $message = [
                'conversation_id' => $conversation_id,
                'sender_id' => $formUserId,
                'receiver_id' => $toUserId,
                'message_type' => $messageData['type'],//可以是 text, image, file, order, product'
                'content' => $messageData['content'],
                'status' => 'success',
            ];
            $messageId = $modelMessage->data_add($message);
            if (!$messageId) {
                throw new Exception('消息保存失败');
            }
            $this->_getSummaryInfo($formUserId, $conversation_id, $messageId, new ChatConversationsSummary(), true);
            $this->_getSummaryInfo($toUserId, $conversation_id, $messageId, new ChatConversationsSummary(), Gateway::isUidOnline($toUserId));

        } catch (Exception $e) {
            Db::rollback();
            bs_log($e->getMessage(), 'error', 'add_check_message.log');
            return self::error_return($e->getMessage());
        }
        Db::commit();

        return self::success_return('保存成功', [
            'conversation_id' => $conversation_id,
        ]);
    }
}
